package packaged;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import models.sys.AdminUser;
import models.sys.Token;
import packaged.storage.Keeper;
import play.Play;
import play.mvc.Http;
import play.mvc.Scope;
import utils.CookiesUtils;

import java.util.UUID;

public class SessionManager {
    private static final String USER_SESSION_FLAG = "USER_LOGIN_FLAG_";
    private static final String USER_BROWSER_FLAG = "USER_BROWSER_FLAG_";

    private static Scope.Session getSession() {
        return Scope.Session.current();
    }

    private static String getSessionId() {
        return getSession().getId();
    }

    /**
     * 检查会话是否到期
     *
     * @return
     */
    public static boolean sessionIsExpire() {
        return !Keeper.has(USER_SESSION_FLAG + getSessionId());
    }

    public static void sessionIncreaseExpire() {
        Keeper.exp(USER_SESSION_FLAG + getSessionId(),"30mn");
    }

    public static void setSession(AdminUser user, boolean remember) {
        Keeper.set(USER_SESSION_FLAG + getSessionId(), user.toJSON().toString());
        if (remember) {
            //使用标识符与Token来确认唯一的浏览器
            //从Cookie中获取Flag标识符,对浏览器进行确认
            String flag = CookiesUtils.getCookie(Http.Request.current(), USER_BROWSER_FLAG);
            if (flag == null) {
                flag = UUID.randomUUID().toString();
                CookiesUtils.addCookie(Http.Response.current(), USER_BROWSER_FLAG, flag, (365 * 24 * 60 * 60));
            }
            String remember_token = UUID.randomUUID().toString();
            JSONObject content = new JSONObject();
            content.put("userid", user.id);
            content.put("username", user.username);
            content.put("password", user.password);
            TokenManager.recordToken(remember_token, flag, content.toString(), Play.configuration.getProperty("remember.overtime"), Token.Type.LOGIN_REMEMBER);
        }
    }

    public static void setAttribute(String key, String value) {
        getSession().put(key, value);
    }

    public static void removeSession() {
        Keeper.del(USER_SESSION_FLAG + getSessionId());
    }

    public static String getAttribute(String key) {
        return getSession().get(key);
    }

    public static JSONObject getUserInfo() {
        if (!sessionIsExpire())
            return JSON.parseObject(Keeper.get(USER_SESSION_FLAG + getSessionId()));
        return null;
    }
}
